package org.expressme.webwind.renderer;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.expressme.webwind.ActionContext;
import org.expressme.webwind.template.TemplateFactory;

/**
 * Render output using template engine.
 * 
 * @author Michael Liao (askxuefeng@gmail.com)
 */
public class TemplateRenderer extends Renderer {

    private String path;
    private String master;

    public TemplateRenderer(String path) {
        this(null,path);
    }

    public TemplateRenderer(String master, String path) {
        this.path = path;
        this.master = master;
    }

    @Override
    public void render(ServletContext context, HttpServletRequest request, HttpServletResponse response) throws Exception {
        
    	Map<String, Object> model=new HashMap<String, Object>();
    	
    	model.put("ViewData", ActionContext.getActionContext().getModel());
    	model.put("Session", ActionContext.getActionContext().getHttpSession());
    	model.put("Cookies", ActionContext.getActionContext().getHttpCookie());
    	
    	if(master!=null){
    		model.put("ChildContent", path);
    		TemplateFactory.getTemplateFactory()
            .loadTemplate(master)
            .render(request, response, model);
    	}
    	else{
	    	TemplateFactory.getTemplateFactory()
	                .loadTemplate(path)
	                .render(request, response, model);
    	}
    }

}
